package com.template.templateuser.domain.service;

import com.template.templateuser.domain.dto.SysMenuDTO;
import com.template.templateuser.domain.dto.SysMenuDTO;
import com.template.templateuser.domain.mapper.SysMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Override
    public List<SysMenuDTO> getSysMenuListTree() {
        List<SysMenuDTO> sysMenuAllList = sysMenuMapper.getSysMenuAllList();
        if(sysMenuAllList!=null&&sysMenuAllList.size()>0){
            Map<Long, List<SysMenuDTO>> collect = sysMenuAllList.stream()
                    .collect(Collectors.groupingBy(SysMenuDTO::getParentId));
            List<SysMenuDTO> allFirstParent = sysMenuAllList.stream().
                    filter(a -> a.getParentId().equals(0L)).collect(Collectors.toList());
            //
            for(SysMenuDTO dto:sysMenuAllList){
                dto.setChildren(collect.get(dto.getId()));
            }
            for(SysMenuDTO dto:allFirstParent){
                dto.setChildren(collect.get(dto.getId()));
            }
            return allFirstParent;
        }
        return null;
    }

    @Override
    public List<SysMenuDTO> getSysMenuListByParentId(Long parentId) {

        return sysMenuMapper.getSysMenuListByParentId(parentId);
    }

    @Override
    public int saveSysMenu(SysMenuDTO sysMenuDTO) {
        return sysMenuMapper.save(sysMenuDTO);
    }

    @Override
    public int updateSysMenu(Long id, SysMenuDTO sysMenuDTO) {
        sysMenuDTO.setId(id);
        return sysMenuMapper.updateById(sysMenuDTO);
    }

    @Override
    public SysMenuDTO querySysMenu(Long id) {
        return sysMenuMapper.findSysMenuById(id);
    }

    @Override
    public int deleteSysMenu(Long id) {
        SysMenuDTO sysMenuDTO=new SysMenuDTO();
        sysMenuDTO.setId(id);
        sysMenuDTO.setDeleted(1);
        return sysMenuMapper.updateById(sysMenuDTO);
    }
}
